package com.food.msgupdownbackend.application;

import com.food.msgupdownbackend.port.inbound.ImgUseCase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 实现ImgUseCase
 * 负责上传下载的主要逻辑
 * @author 24270
 */
@Service
public class ImgApplicationService implements ImgUseCase {
    private RustTemplateService rustService;
    /**
     * 文件保存路径
     */
    @Value("${sava_path}")
    private String savaPath;

    private String newFileName = "";

    @Autowired
    public ImgApplicationService(RustTemplateService rustService) {
        this.rustService = rustService;
    }

    @Override
    public String upload(MultipartFile file, HttpServletRequest request, String id) throws IOException {
        // 文件路径
        String path = null;
        double fileSize = file.getSize();
        System.out.println("文件的大小是"+ fileSize);

        byte[] sizebyte=file.getBytes();
        System.out.println("文件的byte大小是"+ Arrays.toString(sizebyte));



        // 判断上传的文件是否为空
        if (file != null) {
            // 文件类型
            String type = null;
            // 文件原名称
            String fileName = file.getOriginalFilename();
            System.out.println("上传的文件原名称:" + fileName);
            // 判断文件类型
            assert fileName != null;
            type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            // 判断文件类型是否为空
            if (type != null) {

                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {

                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                    
                    // 获取文件后缀
                    String fileType=fileName.substring(fileName.lastIndexOf("."));
                    System.out.println("文件后缀：" + fileType);
                    
                    // 重命名图片
                    newFileName = UUID.randomUUID().toString() + fileType;
                    
                    // 设置存放图片文件的路径
                    path = savaPath + newFileName;
                    System.out.println("存放图片文件的路径:" + path);

                    // 转存文件到指定的路径
                    file.transferTo(new File(path));
                    System.out.println("文件成功上传到指定目录下");

                    List<String> list = new ArrayList<String>();
                    list.add(newFileName);
                    rustService.uploadImgWithAliment(id, list);

                    return "文件成功上传到指定目录下，文件名为" + newFileName;
                }

            } else {
                System.out.println("不是我们想要的文件类型,请按要求重新上传");
                return "不是我们想要的文件类型,请按要求重新上传";
            }
        } else {
            System.out.println("文件类型为空");
            return "文件类型为空";
        }

        return "已经成功上传到指定目录" + newFileName;
    }

    @Override
    public String download(String imgName, HttpServletRequest request, HttpServletResponse response) {

        String fileUrl = savaPath + imgName;

        if (fileUrl != null) {
            File file = new File(fileUrl);
            if (file.exists()) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                // 设置文件名
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + imgName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
}
